package com.platform.netty.tcp;


import com.platform.common.config.Global;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.netty.tcp.initializer.TcpServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @author: [青衫] 'QSSSYH@QQ.com'
 * @Date: 2019-07-04 14:05
 * @Description: < 点烟器款 >
 */
@Slf4j
@Component
@Order(value = 1)
public class TcpServer implements CommandLineRunner {
    //boss事件轮询线程组
    //处理Accept连接事件的线程，这里线程数设置为1即可，netty处理链接事件默认为单线程，过度设置反而浪费cpu资源
    private EventLoopGroup boss = new NioEventLoopGroup(1);
    //worker事件轮询线程组
    //处理hadnler的工作线程，其实也就是处理IO读写 。线程数据默认为 CPU 核心数乘以2
    private EventLoopGroup worker = new NioEventLoopGroup();

    @Autowired
    private TcpServerInitializer tcpServerInitializer;

    @Autowired
    private RedisUtil redisUtil;

    //与客户端建立连接后得到的通道对象
    private Channel channel;

    /**
     * 开启Netty tcp server服务
     *
     * @return
     */
    public ChannelFuture start(int port) throws Exception {
        //启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //组配置，初始化ServerBootstrap的线程组
        serverBootstrap.group(boss, worker)
                ///构造channel通道工厂//bossGroup的通道，只是负责连接
                .channel(NioServerSocketChannel.class)
                //设置通道处理者ChannelHandler////workerGroup的处理器
                .childHandler(tcpServerInitializer)
                //保持连接数
                .option(ChannelOption.SO_BACKLOG, 1024)
                //数据长度
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 2048, 65536))
                //启用心跳保活机制，tcp，默认2小时发一次心跳
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        //Future：异步任务的生命周期，可用来获取任务结果
        //绑定端口，开启监听，同步等待
        ChannelFuture channelFuture = serverBootstrap.bind(port).syncUninterruptibly();
        if (channelFuture != null && channelFuture.isSuccess()) {
            log.info("TCP服务器启动成功, port = {}", port);
            //获取通道
            channel = channelFuture.channel().closeFuture().sync().channel();//获取通道
        } else {
            log.error("TCP服务器启动失败");
        }
        return channelFuture;
    }

    /**
     * 停止Netty tcp server服务
     */
    @PreDestroy
    public void destroy() {
        if (channel != null) {
            channel.close();
            redisUtil.hdelAll("sys-netty");
        }
        try {
            Future<?> future = worker.shutdownGracefully().await();
            if (!future.isSuccess()) {
                log.error("netty tcp workerGroup shutdown fail, {}", future.cause());
            }
            Future<?> future1 = boss.shutdownGracefully().await();
            if (!future1.isSuccess()) {
                log.error("netty tcp bossGroup shutdown fail, {}", future1.cause());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("TCP服务器关闭");
    }

    @Override
    @Async
    public void run(String... args) throws Exception {
        this.start(8888);
    }
}
